"""
    Created By Khun on 2020/4/7
"""

__author__ = 'Khun'

from flask import render_template, request, redirect, url_for, abort, flash, current_app
from flask_login import login_required
from sqlalchemy import desc, or_

from app.forms.wechat import ManageForm
from app.models import db, Throw, Manage
from app.vipadmin import vipadmin
from app.forms.wechat import SearchForm


@vipadmin.route('/manage/list/<int:page>', methods=['GET', 'POST'])
@login_required
def manage_list(page):
    """ 管理 """
    page_data = Manage.query.order_by(desc(Manage.tid)).paginate(page=page, per_page=current_app.config['PAGE_SIZE'])
    return render_template('manage/manage_list.html', page_data=page_data)


@vipadmin.route('/manage/add', methods=['GET', 'POST'])
@login_required
def manage_add():
    form = ManageForm()
    tem_id = Throw.query.all()

    if request.method == 'POST' and form.validate_on_submit():
        manage = Manage()
        manage.set_attr(form.data)
        with db.auto_commit():
            db.session.add(manage)
        flash('新增成功', 'success')
        return redirect(url_for('vipadmin.manage_list', page=1))
    elif form.errors:
        flash('检查数据是否有误', 'danger')
    return render_template('manage/manage_add.html', form=form, tem_id=tem_id)


@vipadmin.route('/manage/delete<int:tid>', methods=['GET', 'POST'])
@login_required
def manage_delete(tid):
    manage_obj = Manage.query.filter_by(tid=tid).first()

    if request.method == 'POST' and manage_obj is None:
        return 'no'
    with db.auto_commit():
        db.session.delete(manage_obj)
    flash('删除成功', 'success')

    return redirect(url_for('vipadmin.manage_list', page=1))


@vipadmin.route('/manage/edit/<tid>', methods=['GET', 'POST'])
@login_required
def manage_edit(tid):
    manage_obj = Manage.query.filter_by(tid=tid).first()
    tem_id = Throw.query.all()

    if request.method == 'POST' and manage_obj is None:
        abort(404)

    data = ManageForm(obj=manage_obj)

    if request.method == 'POST' and data.validate_on_submit():
        manage_obj.set_attr(data.data)

        with db.auto_commit():
            db.session.add(manage_obj)
        flash('修改成功', 'success')
        return redirect(url_for('vipadmin.manage_list', page=1))
    elif data.errors:
        flash('检查数据是否有误', 'danger')

    return render_template('manage/manage_edit.html', data=data, manage_obj=manage_obj, tem_id=tem_id)


@vipadmin.route('/manage/search', methods=['GET'])
@login_required
def manage_search():
    """ 域名或者微信号搜索 """
    form = SearchForm(request.args)
    result = []
    q = ''
    if form.validate():
        q = form.q.data.strip()
        page = form.page.data
        result = Manage.query.filter(
            or_(Manage.web_url.like('%' + q + '%'),
                Manage.wechat.like('%' + q + '%'))
        ).order_by(desc(Manage.tid)).paginate(page=page, per_page=current_app.config['PAGE_SIZE'])
    try:
        return render_template('manage/search_result.html', page_data=result, q=q)
    except Exception as e:
        return '<h2 style="color:red;text-align:center">搜索内容不能为空,请手动返回，重新搜索！</h2>'
